package com.framework.controller.index;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.print.DocFlavor.STRING;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.framework.entity.ResFormMap;
import com.framework.annotation.SystemLog;
import com.framework.entity.ConsoleuserFormMap;
import com.framework.entity.LogFormMap;
import com.framework.entity.base.FormMap;
import com.framework.entity.view.DSAuthInfoViewFormMap;
import com.framework.plugin.PageView;
import com.framework.util.ClassUtil;
import com.framework.util.Common;
import com.framework.util.EhcacheUtils;

/**
 * 
 * @author framework Email：g5874589652@126.com date：2015-2-17
 */
public class BaseController {
	private final String pageName = "com.framework.entity";
	private final String viewpageName = "com.framework.entity.view";
	private final String default_method = "findByNames";
	public static Logger logger = LogManager.getLogger("BaseController");
	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

	@SuppressWarnings("hiding")
	public static <T> Logger getLogger(Class<T> class1) {
		logger = LogManager.getLogger(class1);
		return logger;
	}

	public PageView pageView = null;

	public PageView getPageView(String pageNow, String pageSize, String start) {
		if (Common.isEmpty(pageNow)) {
			pageView = new PageView(1);
		} else {
			pageView = new PageView(Integer.parseInt(pageNow));
		}
		if (Common.isEmpty(pageSize)) {
			pageSize = "10";
		}
		if (Common.isEmpty(start)) {
			start = "0";
		}
		pageView.setStart(Integer.parseInt(start));
		pageView.setLength(Integer.parseInt(pageSize));
		return pageView;
	}

	// @ExceptionHandler(RuntimeException.class)
	public String operateExp(RuntimeException ex, HttpServletRequest request) {
		System.out.println("this is for test");
		// mod.addAttribute("err", ex.getMessage());
		// //ExceptionHandler处理异常时，Model，是不能用的，否则会不起作用，这里用了HttpServletRequest
		request.setAttribute("err", ex.getMessage());
		return "public/error";
	}

	// @ExceptionHandler(Exception.class)
	public String operateExp(Exception ex, HttpServletRequest request) {
		System.out.println("this is for test");
		// mod.addAttribute("err", ex.getMessage());
		// //ExceptionHandler处理异常时，Model，是不能用的，否则会不起作用，这里用了HttpServletRequest
		request.setAttribute("err", ex.getMessage());
		return "public/error";
	}

	
	
	
	// TODO
	public FormMap<String, Object> getSpecialFormMap() throws Exception {
		Class<? extends FormMap<String, Object>> iclass = getSpecialClass();
		FormMap<String, Object> formMap = getMapformDataMap(iclass, getMapFromRequest());
		return formMap;
	}

	// TODO
	@SuppressWarnings("unused")
	public FormMap<String, Object> getSpecialFormMap(Class<? extends FormMap<String, Object>> iclass)
			throws Exception {
		@SuppressWarnings("unchecked")
		FormMap<String, Object> formMap = getMapformDataMap(FormMap.class, getMapFromRequest());
		return formMap;
	}

	@SuppressWarnings("unchecked")
	public Class<? extends FormMap<String, Object>> getSpecialClass() throws Exception {
		String className = null;
		Class<? extends FormMap<String, Object>> iclass = null;
		List<String> classList = ClassUtil.getClassName(pageName);

		for (String iclassName : classList) {
			if (iclassName.toLowerCase().contains(getClassName().toLowerCase())) {
				className = iclassName;
				iclass = (Class<? extends FormMap<String, Object>>) Class.forName(className);
				return iclass;
			}
		}
		return iclass;
	}

	public Method getSpecialMethod() throws Exception {
		Class<? extends FormMap<String, Object>> class1 = getSpecialClass();

		FormMap<String, Object> iFormMap = getMapformDataMap(class1, getMapFromRequest());
		String methodName = iFormMap.get("ivk_method") == null ? default_method : iFormMap.getStr("ivk_method");
		Method method = class1.getMethod(methodName);
		return method;
	}

	public PageView getPageResult(String draw, String length, String start) throws Exception {
		FormMap<String, Object> formMap=getSpecialFormMap();
		formMap = toFormMap(formMap, draw, length, start);
		formMap.put("$orderby", getKeyTimeOrder());
		formMap.put("$search", getsearch());
		formMap.put("keyCloumn",  getKeyCloumn());
		pageView=formMap.findByPage_Names(pageView);
		return pageView;
	}
	
	public Object getSpecialResult() throws Exception {
		Method method = getSpecialMethod();
		FormMap<String, Object> formMap = getSpecialFormMap();
		Object object = method.invoke(formMap);
		return object;
	}

	/**
	 * 检验是否为空
	 * 
	 * @author 李品良 创建时间：2016年9月8日 下午5:34:25
	 * @return
	 */
	@RequestMapping("isEmpty")
	@ResponseBody
	public boolean isEmpty() {
		HashMap<String, Object> hashMap = getMapFromRequest();
		ConsoleuserFormMap account = getFormMap(ConsoleuserFormMap.class);
		account = account.findbyFrist();
		if (account == null) {
			return true;
		} else {
			return false;
		}
	}

	public String getClassName() throws ClassNotFoundException {
		HashMap<String, Object> hashMap = getMapFromRequest();
		Set<String> set = hashMap.keySet();
		Iterator<String> iterator = set.iterator();

		String className = hashMap.get("className") == null ? null : hashMap.get("className").toString();
		if (Common.isEmpty(className)) {
			while (iterator.hasNext()) {
				String header = iterator.next();
				int index = header.indexOf("FormMap.") + 8;
				if (index == 7) {

				} else {
					className = header.substring(0, index - 1);
				}
			}
		} else {

		}

		return className;
	}

	/**
	 * 检验手机号码
	 * 
	 * @author 李品良 创建时间：2016年9月8日 下午5:34:25
	 * @return
	 */
	@RequestMapping("checkCellphone")
	@ResponseBody
	public boolean checkCellphone() {
		HashMap<String, Object> hashMap = getMapFromRequest();
		ConsoleuserFormMap account = getFormMap(ConsoleuserFormMap.class);
		account = account.findbyFrist();
		if (account == null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取返回某一页面的按扭组, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>mod by：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspEkko</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-09-07</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 * 
	 * @return Class<T>
	 * @throws Exception
	 */
	public List<ResFormMap> findByRes() {
		// 资源ID
		String id = getPara("id");

		// 获取request
		ResFormMap resQueryForm = new ResFormMap();
		resQueryForm.put("parentId", id);
		resQueryForm.put("userId", Common.findUserSessionId());
		List<ResFormMap> rse = ResFormMap.mapper().findRes(resQueryForm);
		for (ResFormMap resFormMap : rse) {
			Object o = resFormMap.get("description");
			if (o != null && !Common.isEmpty(o.toString())) {
				resFormMap.put("description", Common.stringtohtml(o.toString()));
			}
		}
		return rse;
	}

	public <T> T toFormMap(T t, String pageNow, String pageSize, String start) {
		@SuppressWarnings("unchecked")
		FormMap<String, Object> formMap = (FormMap<String, Object>) t;
		formMap.put("paging", getPageView(pageNow, pageSize, start));
		return t;
	}

	public HashMap<String, Object> getMapFromRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		Enumeration enumeration = request.getParameterNames();
		HashMap<String, Object> map = new HashMap<>();
		while (enumeration.hasMoreElements()) {
			String key = enumeration.nextElement().toString();
			String value = request.getParameter(key);
			map.put(key, value);
		}
		return map;
	}

	public String getIpAddr() {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = this.getRequest().getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = this.getRequest().getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = this.getRequest().getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = this.getRequest().getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request;
	}

	/**
	 * 获取页面传递的某一个参数值, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 */
	public String getPara(String key) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request.getParameter(key);
	}

	/**
	 * 获取页面传递的排序关键字, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 */
	public String getorder() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String dir = request.getParameter("order[0][dir]");
		String orderid = request.getParameter("order[0][column]");
		String orderName = getPara("columns[" + orderid + "][data]");
		if (dir == null || dir.length() == 0) {
			return "";
		} else {
			return "order by " + orderName + " " + dir;
		}
	}

	/**
	 * 获取页面传递的排序时间关键字, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 */
	public String getTimeOrder() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String create_time = null;
		String update_time = null;
		LogFormMap logFormMap = getMapformDataMap(LogFormMap.class, getMapFromRequest());
		String[] names = logFormMap.getAttrNames();
		for (String name : names) {
			System.out.println(name);
		}

		String dir = request.getParameter("order[0][dir]");
		String orderid = request.getParameter("order[0][column]");
		String orderName = getPara("columns[" + orderid + "][data]");
		if (dir == null || dir.length() == 0) {
			return "";
		} else {
			return "order by " + orderName + " " + dir;
		}
	}

	/**
	 * 获取页面传递的search关键字, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 */
	public String getsearch() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String search = request.getParameter("search[value]");
		if (search == null || search.length() == 0) {
			return "";
		} else {
			return search;
		}
	}

	/**
	 * 获取页面传递的search关键字, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 */
	public String getKeyCloumn() {
		int orderid = 0;
		String linkCloumn = "";
		while (Common.isNotEmpty(getPara("columns[" + orderid + "][data]"))) {
			if ("operation".equals(getPara("columns[" + orderid + "][data]"))) {

			} else {
				linkCloumn += getPara("columns[" + orderid + "][data]") + ",";
			}
			orderid++;
		}
		linkCloumn = linkCloumn.substring(0, linkCloumn.length() - 1);
		return linkCloumn;
	}

	/**
	 * 更新操作最优 创建次之
	 * 
	 * @author Lyon 创建时间：2016年12月3日 下午2:12:30
	 * @param mode
	 * @return
	 */
	public String getKeyTimeOrder(int mode) {
		String result = "";
		String keyClounm = getKeyCloumn();

		String[] liStrings = keyClounm.split(",");
		for (String key : liStrings) {
			String lower_orderName = key.toLowerCase();
			if (lower_orderName.contains("time") || lower_orderName.contains("date")) {
				if (lower_orderName.contains("update")) {
					if (mode != 0) {
						result = "order by " + lower_orderName + " " + "asc";
					} else {
						result = "order by " + lower_orderName + " " + "desc";
					}
					return result;
				}
				// create
				else {
					if (mode != 0) {
						result = "order by " + lower_orderName + " " + "asc";
					} else {
						result = "order by " + lower_orderName + " " + "desc";
					}
				}
			}
		}

		if (Common.isEmpty(result)) {
			result = getorder();
		}
		return result;
	}

	/**
	 * 更新操作最优 创建次之
	 * 
	 * @author Lyon 创建时间：2016年12月3日 下午2:12:30
	 * @param mode
	 * @return
	 */
	public String getKeyTimeOrder() {
		return getKeyTimeOrder(0);
	}

	/**
	 * 获取页面传递的某一个数组值, <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 * 
	 * @return Class<T>
	 * @throws Exception
	 */
	public String[] getParaValues(String key) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		return request.getParameterValues(key);
	}
	/*
	 * @ModelAttribute 这个注解作用.每执行controllor前都会先执行这个方法
	 * 
	 * @author framework Email：g5874589652@126.com date：2015-4-05
	 * 
	 * @param request
	 * 
	 * @throws Exception
	 * 
	 * @throws
	 */
	/*
	 * @ModelAttribute public void init(HttpServletRequest request){ String path
	 * = Common.BACKGROUND_PATH; Object ep =
	 * request.getSession().getAttribute("basePath"); if(ep!=null){
	 * if(!path.endsWith(ep.toString())){ Common.BACKGROUND_PATH =
	 * "/WEB-INF/jsp/background"+ep; } }
	 * 
	 * }
	 */

	/**
	 * 获取传递的所有参数, 反射实例化对象，再设置属性值 通过泛型回传对象. <br/>
	 * <b>author：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspframework</b><br/>
	 * <b>date：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-01</b><br/>
	 * <b>version：</b><br/>
	 * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0</b>
	 * 
	 * @return Class<T>
	 * @throws Exception
	 */
	public <T> T getFormMap(Class<T> clazz) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		@SuppressWarnings("unchecked")
		Enumeration<String> en = request.getParameterNames();
		T t = null;
		try {
			t = clazz.newInstance();
			@SuppressWarnings("unchecked")
			FormMap<String, Object> map = (FormMap<String, Object>) t;
			while (en.hasMoreElements()) {
				String nms = en.nextElement().toString();
				if (nms.endsWith("[]")) {
					String[] as = request.getParameterValues(nms);
					if (as != null && as.length != 0 && as.toString() != "[]") {
						String mname = t.getClass().getSimpleName().toUpperCase().trim();
						if (nms.toUpperCase().startsWith(mname)) {
							nms = nms.substring(nms.toUpperCase().indexOf(mname) + 1);
							map.put(nms, as);
						}
					}
				} else {
					String as = request.getParameter(nms).trim();
					// if(!Common.isEmpty(as)){
					String mname = t.getClass().getSimpleName().toUpperCase();
					if (nms.toUpperCase().startsWith(mname)) {
						nms = nms.substring(mname.length() + 1);
						map.put(nms, as);
						// }
					}

				}
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 获取传递的所有参数, 反射实例化对象，再设置属性值 通过泛型回传对象.
	 * 
	 * @author 李品良
	 * @param clazz
	 * @param hashMap
	 * @return
	 */
	public <T> T getMapformDataMap(Class<T> clazz, HashMap<String, Object> hashMap) {
		T t = null;
		Set<String> set = hashMap.keySet();
		Iterator<String> iterator = set.iterator();
		try {
			t = clazz.newInstance();
			@SuppressWarnings("unchecked")
			FormMap<String, Object> formMap = (FormMap<String, Object>) t;
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				String value = hashMap.get(key).toString();
				formMap.put(key, value);
			}
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return t;

	}

	/*
	 * 按钮上方按钮方法
	 * 
	 * @return List<ResFormMap>
	 */
	public List<ResFormMap> getButtomM(List<ResFormMap> res) {
		List<ResFormMap> rs = new ArrayList<ResFormMap>();
		for (int i = 0; i < res.size(); i++) {
			if (res.get(i).getStr("type").equals("2")) {
				rs.add(res.get(i));
			}
		}
		return rs;
	}

	/*
	 * 按钮上方按钮方法
	 * 
	 * @return String
	 */
	public String getButtomB(List<ResFormMap> res) {
		String rs = "";
		for (int i = 0; i < res.size(); i++) {
			if (res.get(i).getStr("type").equals("3")) {
				rs = rs + " " + res.get(i).getStr("description");
			}
		}
		return rs;
	}
}